<!DOCTYPE html>
<html>
    <head>
        <title>天气预报</title>
        <meta charset="utf-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
        <style>
            div.w1{
                height: 345px;
                width: 572px;
                border: 1px solid #3498db; 
                border-radius: 5px;
                background-image: url(./背景2.webp.jpg);
                background-size: 100% 100%;
                background-color: aqua;
                box-shadow: 0 5px 15px rgba(0,0,0,0.2);
                font-family: 'Microsoft YaHei', sans-serif;
                color: white;
                position: relative;
                overflow: hidden;
            }
            div.top{
                height: 20.67px;
                width: 540px;
                margin-left: 16px;
                position: relative;
                top: 5px;
                border-radius: 5px;
            }
            div.top_l{
                width: 60px;
                height: 20.67px;
                border-radius: 5px;
                float: left;
                font-weight: bold;
                font-size: 16px;
                color: #fff;
            }
            div.top_r{
                width: 120px;
                height: 20.67px;
                border-radius: 5px;
                float: right;
                font-size: 13px;
                text-align: center;
                line-height: 20.67px;
                color: #f0f0f0;
            }
            div.center{
                width: 540px;
                height: 64px;
                position: relative;
                margin-left: 16px;
                margin-top: 15px;
                border-radius: 5px;
            }
            div.c1{
                width: 97.19px;
                height: 64px;
                border-radius: 5px;
                float: left;
            }
            div.c2{
                width: 180px;
                height: 56.67px;
                border-radius: 5px;
                float: left;
                position: relative;
                top: 3px;
                font-size: 13px;
            }
            div.c3{
                width: 150px;
                height: 50px;
                float: left;
                line-height: 50px;
                margin-left: 120px;
                margin-top: -50px;
            }
            button.button1{
                width: 极客时间  60px;
                height: 25px;
                background-color: #3498db;
                border: none;
                border-radius: 10px;
                position: relative;
                top: -34.5px;
                left: 45px;
                color: white;
                font-weight: bold;
                cursor: pointer;
                transition: background-color 0.3s;
            }
            button.button1:hover {
                background-color: #2980b9;
            }
            input.input1{
                position: relative;
                top: 15px;
                display: inline-block;
                left: -70px;
                height: 20px;
                width: 100px;
                border: 1px solid #3498db;
                border-radius: 3px;
                padding: 0 5px;
                background: rgba(255,255,255,0.2);
                color: white;
            }
            input.input1::placeholder {
                color: rgba(255,255,255,0.7);
            }
            div.c2_top{
                font-size: 14px;
                text-align: center;
                width: 180px;
                height: 16.67px;
                border-radius: 5px;
            }
            div.c2_bottom{
                width: 180px;
                height: 24px;
                border-radius: 5px;
                position: relative;
                top: 5px;
                text-align: center;
            }
            div.bottom{
                width: 540px;
                height: 166px;
                margin-left: 16px;
                margin-top: 12px;
                display: flex;
                justify-content: space-between;
                padding-top: 10px;
            }
            .forecast-day {
                width: 70px;
                text-align: center;
                padding: 5px;
                background: rgba(255,255,255,0.1);
                border-radius: 5px;
                backdrop-filter: blur(3px);
            }
            .forecast-date {
                font-size: 12px;
                margin-bottom: 5px;
            }
            .forecast-weather {
                font极客时间 size: 14px;
                margin: 5px 0;
            }
            .forecast-temp {
                font-size: 12px;
                margin-top: 5px;
            }
            span.s1{
                font-size: 13px;
                text-align: center;
                line-height: 20.67px;
                position: relative;
                top: -2px;
            }
            span.sc1{
                font-size: 62px;
                line-height: 64px;
                float: left;
                text-shadow: 0 0 10px rgba(255,255,255,0.5);
            }
            span.sc2{
                font-size: 20px;
                line-height: 34px;
                margin-left: 2px;
                float: left;
                text-align: center;
                font-size: 13px;
                line-height: 24px;
            }
            p.p1{
                position: relative;
                top: -13px;
            }
            .weather-icon {
                width: 40px;
                height: 40px;
                margin: 0 auto;
                background-size: contain;
                background-repeat: no-repeat;
                font-size: 28px;
                line-height: 40px;
            }
            .aqi-info {
                background: rgba(0,0,0,0.2);
                padding: 2px 8px;
                border-radius: 10px;
                display: inline-block;
                position: relative;
                left: 80px;
                top: -22px;
            }
            .loading {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                color: white;
                font-size: 18px;
                display: none;
                z-index: 100;
            }
            .error-message {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(255,0,0,0.7);
                padding: 10px 20px;
                border-radius: 5px;
                display: none;
                z-index: 100;
            }
            
            /* 折线图容器 - 按图片样式 */
            .chart-container {
                width: 572px;
                height: 250px;
                margin-top: 20px;
                background: white;
                border-radius: 10px;
                box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            }
            
            #tempChart {
                width: 100%;
                height: 100%;
            }
            
            /* 整体布局容器 */
            .container {
                display: flex;
                flex-direction: column;
                align-items: center;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="w1">
                <div class="loading">加载中...</div>
                <div class="error-message"></div>
                
                <div class="top">
                    <div class="top_l">
                        <span class="s1">都匀市</span>
                    </div>
                    <div class="top_r">
                        <p class="p1">
                            <span class="current-date">06月03日</span> 
                            <span class="s2">|</span>
                            <span class="week-day">周二</span>
                        </p>
                    </div>
                </div>
                <div class="center">
                    <div class="c1">
                        <span class="sc1">20</span>
                        <span class="sc2">℃</span>
                    </div>
                    <div class="c2">
                        <div class="c2_top">
                            <span class="weather-status">阴&nbsp;</span>
                            <span class="weather-divider">|</span>
                            <span class="weather-wind">&nbsp;东北风 2级</span>
                        </div>
                        <div class="c2_bottom">
                            <span class="aqi-info">优 28</span>
                        </div>
                    </div>
                    <div class="c3">
                        <input type="text" class="input1" placeholder="输入城市名称">
                        <button class="button1">查询</button>
                    </div>
                </div>
                <div class="bottom">
                    <!-- 天气预报区域将由JS动态生成 -->
                </div>
            </div>
            
            <!-- 折线图容器 - 纯白色背景 -->
            <div class="chart-container">
                <div id="tempChart"></div>
            </div>
        </div>
       
       <script>
        // 高德天气API Key
        const API_KEY = 'b42b9edbc77613c4ca1bd8dc2e3bd1d8';
        
        // 获取DOM元素
        const queryBtn = document.querySelector('.button1');
        const cityInput = document.querySelector('.input1');
        const cityNameEl = document.querySelector('.top_l .s1');
        const currentDateEl = document.querySelector('.current-date');
        const weekDayEl = document.querySelector('.week-day');
        const tempEl = document.querySelector('.sc1');
        const weatherStatusEl = document.querySelector('.weather-status');
        const weatherWindEl = document.querySelector('.weather-wind');
        const aqiEl = document.querySelector('.aqi-info');
        const forecastContainer = document.querySelector('.bottom');
        const loadingEl = document.querySelector('.loading');
        const errorEl = document.querySelector('.error-message');
        
        // 天气图标映射
        const weatherIcons = {
            '晴': '☀️',
            '多云': '⛅',
            '阴': '☁️',
            '阵雨': '🌦️',
            '雷阵雨': '⛈️',
            '小雨': '🌧️',
            '中雨': '🌧️',
            '大雨': '🌧极客时间',
            '暴雨': '🌧️',
            '雨夹雪': '🌨️',
            '小雪': '❄️',
            '中雪': '❄️',
            '大雪': '❄️',
            '雾': '🌫️',
            '霾': '😷',
            '雷雨': '⛈️'
        };
        
        // 风向映射
        const windDirections = {
            '0': '无持续风向',
            '1': '东北风',
            '2': '东风',
            '3': '东南风',
            '4': '南风',
            '5': '西南风',
            '6': '西风',
            '7': '西北风',
            '8': '北风',
            '9': '旋转风'
        };
        
        // 初始化页面
        function initPage() {
            // 设置当前日期
            const now = new Date();
            const month = (now.getMonth() + 1).toString().padStart(2, '0');
            const date = now.getDate().toString().padStart(2, '0');
            const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
            const weekDay = weekDays[now.getDay()];
            
            currentDateEl.textContent = `${month}月${date}日`;
            weekDayEl.textContent = `周${weekDay}`;
            
            // 查询天气
            getWeatherData('都匀');
        }
        
        // 获取天气数据
        async function getWeatherData(city) {
            try {
                // 显示加载中
                loadingEl.style.display = 'flex';
                errorEl.style.display = 'none';
                
                // 调用高德天气API
                const response = await fetch(
                    `https://restapi.amap.com/v3/weather/weatherInfo?key=${API_KEY}&city=${encodeURIComponent(city)}&extensions=all`
                );
                
                const data = await response.json();
                
                if (data.status === '1' && data.forecasts && data.forecasts.length > 0) {
                    const forecast = data.forecasts[0];
                    
                    // 更新城市名称
                    cityNameEl.textContent = forecast.city;
                    
                    // 更新当前天气
                    const currentWeather = forecast.casts[0];
                    tempEl.textContent = currentWeather.daytemp;
                    
                    // 更新天气状况
                    weatherStatusEl.textContent = currentWeather.dayweather + " ";
                    
                    // 获取风向名称（如API返回数字代码，则转换为文字）
                    let windDirection = currentWeather.daywind;
                    if (windDirections[windDirection]) {
                        windDirection = windDirections[windDirection];
                    }
                    
                    // 更新风力信息
                    weatherWindEl.textContent = ` ${windDirection} ${currentWeather.daypower}级`;
                    
                    // 更新空气质量（模拟数据）
                    const aqi = Math.floor(Math.random() * 50) + 20;
                    aqiEl.textContent = `优 ${aqi}`;
                    
                    // 更新天气预报
                    updateForecast(forecast.casts);
                    
                    // 绘制温度折线图 - 按图片样式
                    drawTemperatureChart(forecast.casts);
                } else {
                    throw new Error(data.info || '无法获取天气数据');
                }
            } catch (error) {
                errorEl.textContent = `错误: ${error.message}`;
                errorEl.style.display = 'block';
                setTimeout(() => {
                    errorEl.style.display = 'none';
                }, 3000);
                console.error('获取天气数据失败:', error);
            } finally {
                loadingEl.style.display = 'none';
            }
        }
        
        // 更新天气预报
        function updateForecast(forecasts) {
            forecastContainer.innerHTML = '';
            
            forecasts.forEach((day, index) => {
                const dayDiv = document.createElement('div');
                dayDiv.className = 'forecast-day';
                
                const dateParts = day.date.split('-');
                const month = dateParts[1];
                const date = dateParts[2];
                const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
                
                // 对日期对象添加一天的偏移，因为第一个数据是今天
                const dateObj = new Date();
                dateObj.setDate(dateObj.getDate() + index);
                const weekDay = weekDays[dateObj.getDay()];
                
                dayDiv.innerHTML = `
                    <div class="forecast-date">${month}/${date} 周${weekDay}</div>
                    <div class="weather-icon">${weatherIcons[day.dayweather] || '☁️'}</div>
                    <div class="forecast-weather">${day.dayweather}</div>
                    <div class="forecast-temp">${day.nighttemp}°~${day.daytemp}°</div>
                `;
                
                forecastContainer.appendChild(dayDiv);
            });
        }
        
        // 绘制温度折线图 - 完全按图片样式
        function drawTemperatureChart(forecasts) {
            // 提取前5天的数据（按图片样式）
            const displayDays = Math.min(forecasts.length, 5);
            const dayData = forecasts.slice(0, displayDays);
            
            // 提取数据 - 白天温度
            const dates = [];
            const dayTemps = [];
            
            dayData.forEach(day => {
                const dateParts = day.date.split('-');
                dates.push(`${dateParts[1]}/${dateParts[2]}`);
                dayTemps.push(parseInt(day.daytemp));
            });
            
            // 初始化 ECharts 实例
            const chartDom = document.getElementById('tempChart');
            const myChart = echarts.init(chartDom);
            
            // 按照图片样式配置图表
            const option = {
                // 纯白背景
                backgroundColor: '#ffffff',
                
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '15%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    // 隐藏X轴标签（按图片样式）
                    axisLabel: {
                        show: false
                    },
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '温度 (°C)',
                    nameTextStyle: {
                        color: '#333',
                        fontSize: 12
                    },
                    // 设置18-33度的Y轴刻度，每3度一个刻度
                    min: 18,
                    max: 33,
                    interval: 3,
                    axisLine: {
                        lineStyle: {
                            color: '#333'
                        }
                    },
                    axisLabel: {
                        color: '#333',
                        fontSize: 12
                    }
                },
                series: [
                    {
                        name: '白天温度',
                        type: 'line',
                        data: dayTemps,
                        // 黑色线条
                        lineStyle: {
                            color: '#000',
                            width: 1
                        },
                        // 红色数据点
                        itemStyle: {
                            color: '#ff0000'
                        },
                        // 实心圆点
                        symbol: 'circle',
                        symbolSize: 8,
                        // 不显示数据标签（按图片样式）
                        label: {
                            show: false
                        }
                    }
                ],
                // 移除所有额外元素（按图片样式）
                legend: { show: false },
                tooltip: { show: false },
                animation: true,
                animationDuration: 2000
            };
            
            // 使用刚指定的配置项和数据显示图表
            myChart.setOption(option);
            
            // 响应窗口大小变化
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }
        
        // 绑定查询按钮事件
        queryBtn.addEventListener('click', () => {
            const city = cityInput.value.trim();
            if (city) {
                getWeatherData(city);
            } else {
                errorEl.textContent = '请输入城市名称';
                errorEl.style.display = 'block';
                setTimeout(() => {
                    errorEl.style.display = 'none';
                }, 2000);
            }
        });
        
        // 绑定回车键事件
        cityInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                queryBtn.click();
            }
        });
        
        // 初始化页面
        window.addEventListener('DOMContentLoaded', initPage);
       </script>
    </body>
</html>